import os
import pandas as pd


class DataOperation:
    def __init__(self, path, sheet_name=None, con=None):
        try:
            if path.endswith(".csv"):
                self.data = pd.read_csv(path)
            elif path.endswith(".xls") or path.endswith(".xlsx"):
                self.data = pd.read_excel(path, sheet_name)
            elif path.endswith(".sql"):
                self.data = pd.read_sql(path, con)
            else:
                print("不支持的数据类型,请选择.csv|.xls|.xlsx|.sql")
        except FileNotFoundError:
            print("文件不存在")

    def data_to_list(self):
        try:
            return self.data.values.tolist()
        except AttributeError:
            print("对象创建失败")

    def data_to_dict(self):
        try:
            return [self.data.loc[i].to_dict() for i in self.data.index.values]
        except AttributeError:
            print("对象创建失败")


if __name__ == '__main__':
    file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data/lj_dta.csv")
    do = DataOperation(file_path)
    print(do.data_to_list())
    print(do.data_to_dict())
